package com.beaut.project.interceptor;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.beaut.project.util.ServletUtility;
import com.beaut.project.util.Utility;


/**
 * 权限拦截器
 *
 */
public class PermissionInterceptor implements HandlerInterceptor{
	private ApplicationContext applicationContext;
	
	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object arg2) throws Exception {
		String url = request.getRequestURI();
		url = url.substring(url.indexOf(request.getContextPath())+request.getContextPath().length());
		
		HttpSession session = ((HttpServletRequest) request).getSession();
		boolean isValidSession =ServletUtility.isValidSession(session, "LOGIN_USER"); //验证Session的有效性
//		if(isValidSession){
//			Map<String, Object> sessionMap = (Map<String, Object>)request.getSession().getAttribute("LOGIN_USER");
//			String username = sessionMap.get("username").toString();
//			//需要进行权限判断
//			if(SystemParamUtility.MAP_POWER.get(username) != null && SystemParamUtility.MAP_POWER.get(username).get(url) != null){
//				Map<String,String> map = new HashMap<String,String>();
//				//权限
//				String permission_id = SystemParamUtility.MAP_POWER.get(username).get(url);
//				map.put("permission_id", permission_id);
//				//用户信息
//				map.put("user_id", sessionMap.get("id").toString());
//				//判断该用户是否有该权限
//				ServletContext sc = request.getSession().getServletContext();
//				ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
//				CoreService coreService = (CoreService) ac.getBean("coreService");
//				if(!coreService.checkPermission(map)){
//					if(url.contains(".jsp")){
//						return false;
//					}
//					PrintWriter out = response.getWriter();
//					StringBuffer sb = new StringBuffer("");
//					sb.append("{\"total\":0,\"rows\":[],").append(Utility.rtJson(Utility.RETURN_ERROR, "您没有权限进行此操作！", null).substring(1));
//					out.write(sb.toString());
//					return false;
//				}
//			}
//		}
		return true;
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0,
			HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
			Object arg2, ModelAndView arg3) throws Exception {
		
	}
}
